﻿using System;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Collections.Generic;

namespace Fast2BuildTool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            var dllPath = textBox1.Text;
            var assembly = Assembly.LoadFrom(dllPath);
            var bindType = assembly.GetType(textBox3.Text);
            if (bindType == null)
                throw new Exception("获取类型失败!");
            var method = bindType.GetMethod(textBox4.Text, BindingFlags.Static | BindingFlags.Public);
            IList<Type> list = (IList<Type>)method.Invoke(null,null);
            foreach (var type in list)
            {
                Fast2BuildToolMethod.Build(type, textBox2.Text);
                Fast2BuildToolMethod.BuildArray(type, textBox2.Text);
                Fast2BuildToolMethod.BuildGeneric(type, textBox2.Text);
            }
            MessageBox.Show("生成完成.");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK) 
            {
                textBox1.Text = openFileDialog1.FileName;
                Save();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                textBox2.Text = folderBrowserDialog1.SelectedPath;
                Save();
            }
        }

        void Save() 
        {
            Data data = new Data() { dllpath = textBox1.Text, savepath = textBox2.Text };
            var jsonstr = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            var path = Directory.GetCurrentDirectory() + "data.txt";
            File.WriteAllText(path, jsonstr);
        }

        internal class Data 
        {
            public string dllpath, savepath;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var path = Directory.GetCurrentDirectory() + "data.txt";
            if (File.Exists(path))
            {
                var jsonStr = File.ReadAllText(path);
                var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Data>(jsonStr);
                textBox1.Text = data.dllpath;
                textBox2.Text = data.savepath;
            }
        }
    }
}
